package itsm.isperp.workflow.listener;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.module.entity.bpm.BpmNodeUser;
import itsm.isperp.module.service.bpm.BpmNodeUserService;
import itsm.isperp.module.utils.CandidaterUtils;
import itsm.isperp.workflow.utils.BpmMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;

/**
 * 
 * 消息发送服务任务监听器
 * 
 * @author lizx
 * @date 2013-8-26
 * 
 */
public class MessageServiceTaskListener implements JavaDelegate {

	@Override
	public void execute(DelegateExecution execution) throws Exception {

		ExecutionEntity ent = (ExecutionEntity) execution;
		String nodeId = ent.getActivityId();
		String actDefId = ent.getProcessDefinitionId();
		String businessKey = ent.getBusinessKey();

		String actDefKey = actDefId.split(":")[0];

		BpmNodeUserService bpmNodeUserService = (BpmNodeUserService) ContextHolder
				.getSpringBean("bpmNodeUserService");
		List<BpmNodeUser> users = bpmNodeUserService.findAllByDefIdAndNodeId(
				actDefId, nodeId);
		Map<String, IUser> mapUsers = new HashMap<String, IUser>();
		for (BpmNodeUser user : users) {
			CandidaterUtils.addToCandidaterInProcess(bpmNodeUserService, mapUsers,
					user, ent.getBusinessKey(), actDefKey,
					ent.getProcessInstanceId(), nodeId, execution);
		}

		// 发送消息
		BpmMessageUtils.sendMessages(ent, actDefKey, ent.getActivityId(),
				mapUsers, businessKey);
	}
}
